﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System;

namespace Grinder.Renamer.RenamePlugins
{
    internal sealed class HtmlRenamePlugin : IRenamePlugin
    {
        private static readonly Regex Regex = new Regex(@"(?<=<title.*>)([\s\S]*)(?=</title>)");

        private readonly Dictionary<string, string> _tokens;
        public string Name { get { return "HTML Files"; } }
        public IEnumerable<string> Extensions { get { return new List<string> { "*.HTM", "*.HTML", "*.SHTML" }; } }
        public Dictionary<string, string> Tokens { get { return _tokens; } }
        public System.Drawing.Image Icon { get { return Properties.Resources.html; } }
        public override string ToString() { return string.Format("{0} ({1})", Name, string.Join(",", Extensions.ToArray()).ToLower()); }

        public HtmlRenamePlugin()
        {
            _tokens = new Dictionary<string, string>
                         {
                             {"title", "Document title"}                             
                         };
        }

        public Dictionary<string, object> GetTokens(FileInfo file)
        {
            var dic = new Dictionary<string, object>();

            using (var sr = new StreamReader(file.FullName))
            {
                Match match = Regex.Match(sr.ReadToEnd());
                dic.Add("title", match.Value.Trim().Replace(Environment.NewLine, String.Empty));
            }

            return dic;
        }
    }
}
